﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using GeneralDFS.Common;
using GeneralDFS.DataEntity.Enum;
using GeneralDFS.DataEntity.Config;

namespace GeneralDFS.BusinessLogical.Config
{
    public class ConfigCenter
    {
        private const String ConfigFileName = "serverConfig.xml";
        private readonly DFSConfig _config;

        public ConfigCenter()
        {
            if (_config != null) throw new Exception("the node has already config!");
            if (File.Exists(ConfigFileName))
            {
                LogUtil.LogInfo(String.Format("{0} has found,begin init configCenter!", ConfigFileName));
                var xmlSerializer = new XmlSerializer(typeof(DFSConfig));
                using (var stream = File.Open(ConfigFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    _config = xmlSerializer.Deserialize(stream) as DFSConfig;
                }
            }
            else
            {
                LogUtil.LogInfo(String.Format("{0} has not found,init default config!", ConfigFileName));
                _config = new DFSConfig();
                initConfigWithDefaultValue(_config);
            }
            if (_config != null) _config.TimeCheckPoint = DateTime.Now.LongNow(); //检查配置文件载入成功，设置为最新配置
            SaveToFile();
            LogUtil.LogInfo("ConfigCenter init Success!");
        }

        public ConfigCenter(DFSConfig config)
        {
            _config = config;
        }

        /// <summary>
        /// 获取配置类
        /// </summary>
        /// <returns></returns>
        public DFSConfig GetConfig()
        {
            return _config;
        }

        /// <summary>
        /// 初始化配置文件
        /// </summary>
        /// <param name="config"></param>
        private void initConfigWithDefaultValue(DFSConfig config)
        {
            config.DataNodeConfigs = new List<DataNodeConfig> { new DataNodeConfig { DataNodeDirectory = Path.Combine(System.Environment.CurrentDirectory, "Blocks"), Index = 0, Ip = System.Net.IPAddress.Loopback.ToString(), RpcPort = 8089, ServerName = "DemoDataNode", Type = NodeType.DataNode } };
            config.NameNodeConfigs = new List<NameNodeConfig>{new NameNodeConfig{Ip=System.Net.IPAddress.Loopback.ToString(),RpcPort = 8090,ServerName = "DemoNameNode",Type = NodeType.NameNode,Version = "0"}};
            config.TimeCheckPoint = DateTime.Now.LongNow();
            config.DetailConfig = new DetailConfig
                {
                    BlockSize = 20480000,
                    BuffSize = 2048000,
                    CopyTimes = 3,
                    HeartBeat = 3,
                    Mode = "local"
                };
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        /// <returns></returns>
        public long SaveToFile()
        {
            if(File.Exists(ConfigFileName))
                File.Delete(ConfigFileName);
            using (var stream = File.Create(ConfigFileName))
            {
                var xmlSerializer = new XmlSerializer(typeof(DFSConfig));
                xmlSerializer.Serialize(stream,_config);
            }
            return _config.TimeCheckPoint;
        }

        public NameNodeConfig GetFirstConfig()
        {
            return _config.NameNodeConfigs[0];
        }

    }
}